import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ResultUtils } from 'src/common/utils/result.utils';
import { Repository } from 'typeorm';
import { Banner } from './banner.entity';
import { CreateBannerDto } from './dto/create-banner.dto';
import { GetBannerIdentityDto } from './dto/get-banner-identity-dto';
import { GetBannerDto } from './dto/get-banner.dto';
import { UpdateBannerDto } from './dto/update-banner.dto';
import { BannerResultVo } from './vo/banner.result.vo';

@Injectable()
export class BannerService {
  constructor(@InjectRepository(Banner) private bannerRepository:Repository<Banner>){}
  async create(createBannerDto: CreateBannerDto) {
    const queryBanner = await this.bannerRepository.findOne({
      where:{identity:createBannerDto.identity }
    });
    if(queryBanner) {
      throw new BadRequestException('广告标识重复');
    }
    if(createBannerDto.banners instanceof String){
      try{
        JSON.parse(createBannerDto.banners as string);
      }catch(e){
        throw new BadRequestException('广告内容有误');
      }
    }
    createBannerDto.banners = JSON.stringify(createBannerDto.banners);
    const banner = await this.bannerRepository.create(createBannerDto as Partial<Banner>);
    const result = await this.bannerRepository.save(banner);
    return ResultUtils.success(result.id);
  }

  async findAll(query:GetBannerDto) {
    let {limit,page} = query;
    const queryBuilder = this.bannerRepository.createQueryBuilder('banner').addOrderBy('update_time','DESC');
    if(page) {
      if(!limit) {
        limit = 10
      }
      queryBuilder.take(limit).skip((page-1)*limit);
      const list = await queryBuilder.getManyAndCount();
      return ResultUtils.success({
        list:list[0],
        total:list[1]
      });
    }else {
      return ResultUtils.success(await queryBuilder.getMany());
    }
  }

  async findOne(id: number) {
    const banner = await this.bannerRepository.findOne({ where: {id} });
    let banners = JSON.parse(banner.banners);
    if(banners instanceof Array) {
      banners = banners.sort((a,b)=>{
        if((a.sort||a.sort===0)&&(b.sort||b.sort===0)) {
          return b.sort - a.sort;
        }
      })
    }
    const result:BannerResultVo = {
      id:banner.id,
      identity:banner.identity,
      name:banner.name,
      desc:banner.desc,
      banners:banners,
      status:banner.status,
      create_time:banner.create_time,
      update_time:banner.update_time
    };
    return ResultUtils.success(result);
  }

  async findOneIdentity(query:GetBannerIdentityDto) {
    const banner = await this.bannerRepository.findOne({ where: {identity:query.identity,status:1} });
    let banners = JSON.parse(banner.banners);
    if(banners instanceof Array) {
      banners = banners.sort((a,b)=>{
        if((a.sort||a.sort===0)&&(b.sort||b.sort===0)) {
          return b.sort - a.sort;
        }
      })
    }
    const result:BannerResultVo = {
      id:banner.id,
      identity:banner.identity,
      name:banner.name,
      desc:banner.desc,
      banners:banners,
      status:banner.status,
      create_time:banner.create_time,
      update_time:banner.update_time
    };
    return ResultUtils.success(result);
  }

  async update(id: number, updateBannerDto: UpdateBannerDto) {
    const queryBanner = await this.bannerRepository.findOne({
      where:{identity:updateBannerDto.identity }
    });
    if(queryBanner&&queryBanner.id!==id) {
      throw new BadRequestException('广告标识重复');
    }
    updateBannerDto.banners = JSON.stringify(updateBannerDto.banners);
    const banner = await this.bannerRepository.findOne({ where: {id} });
    const newBanner = this.bannerRepository.merge(banner,updateBannerDto as Partial<Banner>);
    return ResultUtils.success(await this.bannerRepository.save(newBanner));
  }

  async remove(id: number) {
    await this.bannerRepository.delete(id);
    return ResultUtils.success();
  }
}
